#include "dht11.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>

#define MAZPIN 10

int esp32c3_wire_read()
{
        return gpio_get_level(MAZPIN);
}

void esp32c3_wire_write(int val)
{
        gpio_set_level(MAZPIN, val);
}

void esp32c3_dir_set(int dir)
{
        if (dir == OUTPUT)
                gpio_set_direction(MAZPIN, GPIO_MODE_OUTPUT);
        else
                gpio_set_direction(MAZPIN, GPIO_MODE_INPUT);
}

void esp32c3_usleep(int us)
{
        usleep(us);
}

void esp32c3_msleep(int ms)
{
        usleep(1000 * ms);
}

uint64_t esp32c3_uget()
{
        struct timeval tv;
        gettimeofday(&tv, NULL);
        return tv.tv_sec * 1000 * 1000 + tv.tv_usec;
}

void app_main(void)
{
        struct dht11 sensor;
        uint8_t humidity = 0;
        uint8_t temperature = 0;

        /* register the ops */
        sensor.wire.dir_set = esp32c3_dir_set;
        sensor.wire.write = esp32c3_wire_write;
        sensor.wire.read = esp32c3_wire_read;
        sensor.time.delay_us = esp32c3_usleep;
        sensor.time.delay_ms = esp32c3_msleep;
        sensor.time.get = esp32c3_uget;

        while (1) {
                int chk = dht11_read(&sensor, &temperature, &humidity);
                if (EINVAL == chk) {
                        printf("Inval error\n");
                        continue;
                } else if (ECHECKSUM == chk) {
                        printf("Checksum error\n");
                        continue;
                } else if (ETIMEOUT == chk) {
                        printf("Timeout error\n");
                        continue;
                }

                printf("Humidity: %u; Temperature: %u\n", humidity, temperature);
                vTaskDelay(2000 / portTICK_PERIOD_MS);
        }
}
